# -*- coding: utf-8 -*-
import math
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.http_util import retry_request
from zc_core.spiders.base import BaseSpider
from sdszfcg.rules import *


class OrderSpider(BaseSpider):
    name = "order"
    # 订单基础url
    order_url = "http://ggzyjyzx.shandong.gov.cn/wssc/goods/trade?page={}&rows={}&pid={}"

    def __init__(self, batchNo=None, *args, **kwargs):
        super(OrderSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        self.rows = 50

    def start_requests(self):
        # data_list = ItemDataDao().get_batch_data_list(self.batch_no, fields={"_id": 1, "supplierId": 1, "supplierName": 1})
        data_list = SkuPoolDao().get_sku_pool_list(fields={"_id": 1, "supplierId": 1, "supplierName": 1})

        for data in data_list:
            pid = data.get("_id")
            supplier_id = data.get("supplierId")
            supplier_name = data.get("supplierName")
            page = 1
            order_url = self.order_url.format(page, self.rows, pid)
            yield Request(
                url=order_url,
                meta={
                    'reqType': 'order',
                    "pageNo": page,
                    "skuId": pid,
                    'batchNo': self.batch_no,
                    "supplierId": supplier_id,
                    "supplierName": supplier_name
                },
                callback=self.parse_order,
                errback=self.error_back
            )

    def parse_order(self, response):
        if not response.text:
            return None
        res = json.loads(response.text).get('data', {})
        meta = response.meta
        skuId = meta.get("skuId")
        supplier_id = meta.get("supplierId")
        supplier_name = meta.get("supplierName")
        page_no = meta.get("pageNo", 1)
        order_list = res.get("list")
        total = int(res.get('total'))
        total_page = math.ceil(total / self.rows)
        if order_list and len(order_list) > 0:
            orders = parse_order(response)
            yield Box("order_item", self.batch_no, orders)
            self.logger.info('订单: sku=%s, cnt=%s' % (skuId, len(orders)))

            if page_no == 1 and total > self.rows:
                for idx in range(2, total_page + 1):
                    order_url = self.order_url.format(idx, self.rows, skuId)
                    yield Request(
                        url=order_url,
                        meta={
                            'reqType': 'order',
                            "pageNo": idx,
                            "skuId": skuId,
                            'batchNo': self.batch_no,
                            "supplierId": supplier_id,
                            "supplierName": supplier_name
                        },
                        headers={
                            'siteCode': 'sdszfcg'
                        },
                        callback=self.parse_order,
                        errback=self.error_back,
                        priority=50,
                        dont_filter=True
                    )
        else:
            self.logger.info('无单: sku=%s, page=%s' % (skuId, page_no))
